package com.titleevaluation.service;

import com.titleevaluation.entity.AcademicAchievements;
import com.titleevaluation.entity.Application;
import com.titleevaluation.repository.AcademicAchievementsRepository;
import com.titleevaluation.repository.ApplicationRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class AcademicAchievementsService {

    private final AcademicAchievementsRepository academicAchievementsRepository;
    private final ApplicationRepository applicationRepository;

    public AcademicAchievementsService(AcademicAchievementsRepository academicAchievementsRepository, ApplicationRepository applicationRepository) {
        this.academicAchievementsRepository = academicAchievementsRepository;
        this.applicationRepository = applicationRepository;
    }

    public AcademicAchievements createAcademicAchievements(Long applicationId, AcademicAchievements academicAchievements) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        academicAchievements.setApplication(application);
        academicAchievements.setCreatedAt(LocalDateTime.now());
        academicAchievements.setUpdatedAt(LocalDateTime.now());
        return academicAchievementsRepository.save(academicAchievements);
    }

    public List<AcademicAchievements> getAcademicAchievementsByApplicationId(Long applicationId) {
        return academicAchievementsRepository.findByApplicationId(applicationId);
    }

    public Optional<AcademicAchievements> getAcademicAchievementsById(Long id) {
        return academicAchievementsRepository.findById(id);
    }

    public AcademicAchievements updateAcademicAchievements(Long id, AcademicAchievements updatedAcademicAchievements) {
        AcademicAchievements existingAcademicAchievements = academicAchievementsRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("AcademicAchievements not found"));

        existingAcademicAchievements.setAchievementName(updatedAcademicAchievements.getAchievementName());
        existingAcademicAchievements.setAchievementType(updatedAcademicAchievements.getAchievementType());
        existingAcademicAchievements.setIssuingAuthority(updatedAcademicAchievements.getIssuingAuthority());
        existingAcademicAchievements.setIssuingDate(updatedAcademicAchievements.getIssuingDate());
        existingAcademicAchievements.setRemarks(updatedAcademicAchievements.getRemarks());
        existingAcademicAchievements.setUpdatedAt(LocalDateTime.now());

        return academicAchievementsRepository.save(existingAcademicAchievements);
    }

    public void deleteAcademicAchievements(Long id) {
        academicAchievementsRepository.deleteById(id);
    }
}

